<template>
  <Modal
    width="800"
    footer-hide
    v-model="enableMap"
    :transfer="false"
    class-name=".ivu-modal-wrap"
  >
    <RadioGroup @on-change="changeMap" v-model="mapDefault" type="button">
      <Radio label="select">谷歌地图</Radio>
      <Radio label="map" v-if="aMapSwitch">高德地图</Radio>
    </RadioGroup>
    <div>
      <div v-if="mapDefault === 'select'">
        <GmapAutocomplete
          @place_changed="setPlace"
          placeholder="请输入地址或点击地图选择位置"
          style="width: 50%; height: 50px"
        />
      </div>
      <GmapMap
        ref="map"
        :center="center"
        :zoom="zoom"
        style="width: 100%; height: 400px"
        @click="handleMapClick"
      >
        <GmapMarker
          :key="index"
          v-for="(m, index) in markers"
          :position="m.position"
        />
      </GmapMap>
      <div class="footer">
        <Button type="primary" @click="finished">
          {{ $t("confirm") }}
        </Button>
      </div>
      <mapping v-if="mapDefault === 'map'" ref="map" @getAddress="getAddress" />
    </div>
  </Modal>
</template>

<script>
import { aMapSwitch } from "@/config/index";
import mapping from "@/components/map/index.vue";
import * as API_Setup from "@/api/common.js";
export default {
  components: { mapping },
  data() {
    return {
      aMapSwitch,
      enableMap: false,
      center: { lat: 45.508, lng: -73.587 },
      zoom: 11,
      mapDefault: "select",
      data: {
        province: [], //省
        city: [], //市
        area: [], //区
        street: [], //街道
      },
      chiosend: [],
      markers: [],
    };
  },
  mounted() {
    this.chiosend = new Array(4).fill("");
  },
  methods: {
    setPlace(place) {
      console.log(place);
      this.currentPlace = place;
      this.addMarkerFun();
      this.chiosend = place.address_components;
    },
    addMarkerFun() {
      if (this.currentPlace) {
        this.zoom = 17;
        const marker = {
          lat: this.currentPlace.geometry.location.lat(),
          lng: this.currentPlace.geometry.location.lng(),
        };
        this.markers = [];
        this.markers.push({ position: marker });
        this.center = marker;
      }
    },
    // 处理地图点击事件
    async handleMapClick(event) {
      const lat = event.latLng.lat();
      const lng = event.latLng.lng();
      
      // 更新标记位置
      const marker = { lat, lng };
      this.markers = [{ position: marker }];
      this.center = marker;
      
      // 使用谷歌地图的 Geocoder 服务获取地址信息
      const geocoder = new window.google.maps.Geocoder();
      try {
        const response = await geocoder.geocode({ location: { lat, lng } });
        if (response.results && response.results[0]) {
          this.currentPlace = response.results[0];
          this.chiosend = response.results[0].address_components;
        }
      } catch (error) {
        console.error('Geocoding error:', error);
        this.$Message.error('获取地址信息失败');
      }
    },
    geolocate: function () {
      let vm = this;
      navigator.geolocation.getCurrentPosition((position) => {
        vm.center = {
          lat: position.coords.latitude,
          lng: position.coords.longitude,
        };
      });
    },
    open() {
      this.enableMap = true;
      this.init({ id: 0 }, "province");
    },
    changeMap(val) {
      this.mapDefault = val;
    },
    init(val, level = "province", index) {
      if (level == 0) {
        // 说明选择到了街道，将街道id存入数组
        this.chiosend.splice(3, 1, val);
      } else {
        API_Setup.getRegion(val.id).then((res) => {
          if (res.result.length && val.id !== 0) {
            this.chiosend[index] = val;
          } else if (!res.result.length) {
            this.chiosend[index] = val;
          }
          this.data[level] = res.result;
          if (level == "city") {
            this.data.area = [];
            this.data.street = [];
            this.chiosend.splice(1, 3, "", "", "");
          }
          if (level == "area") {
            this.data.street = [];
            this.chiosend.splice(2, 2, "", "");
          }
          if (level == "street") {
            this.chiosend.splice(3, 1, "");
          }
        });
      }
    },
    getAddress(center) {
      this.$emit("callback", {
        type: this.mapDefault,
        data: center,
      });
      this.enableMap = false;
    },
    // 选择完成
    finished() {
      if (!this.chiosend[0]) {
        this.$Message.error("请选择地址");
        return;
      }
      // 使用Set来去重，但保留原始顺序
      let seen = {};
      let result = [];

      this.chiosend.forEach((item) => {
        if (!seen[item.long_name]) {
          seen[item.long_name] = true; // 标记为已看到
          result.push(item); // 添加到结果数组
        }
      });
      const params = result.filter(
        (item) => (item.name = item.long_name),
        (item) => (item.id = item.short_name),
        (item) => item !== "" && item.long_name !== ""
      );
      this.enableMap = false;
      console.log(params);
      this.$emit("callback", {
        type: this.mapDefault,
        data: params,
      });
    },
  },
};
</script>

<style lang="scss">
.selector {
  height: 400px;
  padding: 10px 0;
  display: flex;
}

.selector-item {
  width: 100%;
  flex: 1;
  overflow: auto;
}

.map-item {
  width: 100%;
  padding: 10px;
  border-bottom: 1px solid #eee;
  cursor: pointer;

  &:hover {
    background: #eee;
  }
}

.active {
  background: #eee;
}

.footer {
  text-align: right;
  margin: 10px 0;
}
.ivu-modal-wrap {
  z-index: 999 !important;
}
.ivu-modal-mask {
  z-index: 998 !important;
}
</style>
